package gemini.pollux.ui.client.utils;

import gemini.pollux.ui.client.mvp.gin.PolluxGinjector;
import gemini.pollux.ui.client.page.RootEvent;
import gemini.pollux.ui.client.utils.widgets.dialog.GmnDialog;
import gemini.pollux.ui.client.utils.widgets.dialog.GmnDialog.GmnDialogType;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GuiUtils {

	public static final String DD_MM_YYYY= "dd.MM.yyyy";
	public static final long DURATION = 1000 * 60 * 60 * 24 * 14;

	/**
	 * parse a string to date
	 * @return null if parse error.
	 */
	public static Date format(String date, String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		Date rt = null;
		try {
			rt = dateFormat.parse(date);
		}catch (Exception e) {
			rt = null;
		}
		return rt;
	}

	/**
	 * format a date to string
	 * @return null if parse error.
	 */
	public static String format(Date date, String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		String rt = null;
		try {
			rt = dateFormat.format(date);
		}catch (Exception e) {
			rt = null;
		}
		return rt;
	}
	
	/**
	 * parse a string to date
	 * @return null if parse error.
	 */
	public static Date format(String date){
		return format(date, DD_MM_YYYY);
	}

	/**
	 * format a date to string
	 * @return null if parse error.
	 */
	public static String format(Date date){
		return format(date, DD_MM_YYYY);
	}
	
	public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
	
	/**
	 *  We cannot use Calendar at GWT Client, use below method to subtract
	 * @param date
	 * @param nbSubtract dates from specific date
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static Date subtractDate(Date date, int nbSubtract) {
		Date result = new Date(date.getTime());
		result.setDate(date.getDate() - nbSubtract);
		return result;
	}
	
	@SuppressWarnings("deprecation")
	public static Date addMonth(Date date, int nbAdd) {
		Date result = new Date(date.getTime());
		result.setMonth(date.getMonth() + nbAdd);
		return result;
	}
	
	public static void alert(String message) {
		PolluxGinjector.INSTANCE.getEventBus().fireEvent(
				new RootEvent(RootEvent.ForwardType.UN_MASK));

		GmnDialog dlgConfirm = new GmnDialog(GmnDialogType.ERROR, "Error",
				message, "OK");

		dlgConfirm.show();
	}
	
	public static void info(String message) {
		PolluxGinjector.INSTANCE.getEventBus().fireEvent(
				new RootEvent(RootEvent.ForwardType.UN_MASK));

		GmnDialog dlgConfirm = new GmnDialog(GmnDialogType.INFO, "Information",
				message, "OK");

		dlgConfirm.show();
	}
}
